package com.iking.toolkit.system.service.impl;

import com.iking.toolkit.model.Msg;
import com.iking.toolkit.util.SysUtil;
import com.iking.toolkit.system.dao.MenuMapper;
import com.iking.toolkit.system.model.http.HttpMenuChangeSortReq;
import com.iking.toolkit.system.model.http.HttpMenuModel;
import com.iking.toolkit.system.model.model.Menu;
import com.iking.toolkit.system.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * menu(系统菜单) ServiceImpl
 *
 * @author user
 * @since 2022-10-09
 */
@Service
public class MenuServiceImpl implements MenuService {

    private final Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 菜单信息管理
     */
    @Autowired
    private MenuMapper menuMapper;


    /**
     * @Description: 新增菜单
     * @Param: [req]
     * @return: com.iking.common.model.Msg
     * @Author: wk
     * @Date: 7/2/2020 上午10:03
     */
    @Override
    public Msg insert(Menu req) {
        try {
            req.setMenuId(SysUtil.getUUID());
            req.setIsAdjunct(false);
            int count = menuMapper.insert(req);
            if (count < 1) {
                return Msg.fail("新增菜单失败!");
            }
            return Msg.sucess();
        } catch (Exception e) {
            log.error("新增菜单异常 : " + e);
            return Msg.fail("新增菜单异常!");
        }
    }

    /**
     * @Description: 修改菜单
     * @Param: [req]
     * @return: com.iking.common.model.Msg
     * @Author: wk
     * @Date: 7/2/2020 上午10:05
     */
    @Override
//    @Transactional(isolation = Isolation.READ_UNCOMMITTED)
    public Msg update(Menu req) {
        try {
            Menu model = menuMapper.selectByPrimaryKey(req.getMenuId());
            if (model == null) {
                return Msg.fail("菜单信息不存在!");
            }
            BeanUtils.copyProperties(req, model);
            //设置菜单级别
            int level = 0;
            if ("-1".equals(req.getParentId())) {
                model.setLevel(1);
                level = 1;
            } else {
                Menu parent = menuMapper.selectByPrimaryKey(req.getParentId());
                if (parent != null) {
                    level = parent.getLevel() + 1;
                }
            }
            model.setLevel(level);
            int count = menuMapper.updateByPrimaryKeySelective(model);
            if (count < 1) {
                return Msg.fail("修改菜单失败");
            }
            //循环处理子菜单
            this.updateBatch(model.getMenuId());
            return Msg.sucess();
        } catch (Exception e) {
            log.error("修改菜单异常 : " + e);
            return Msg.fail("修改菜单异常!");
        }
    }

    /**
     * @Description: 递归设置子类菜单的级别
     * @Param: [fId]
     * @return: void
     * @Author: wk
     * @Date: 12/2/2020 下午6:45
     */
    @Transactional(isolation = Isolation.READ_UNCOMMITTED)
    public void updateBatch(String fId) {
        //递归设置子类菜单的级别
        Menu parent = menuMapper.selectByPrimaryKey(fId);
        Integer level = null;
        if (parent != null) {
            List<Menu> menus = menuMapper.selectByParentId(fId);
            if (menus != null && menus.size() != 0) {
                level = (parent.getLevel() + 1);
                menuMapper.updateLevelByParentId(parent.getMenuId(), level);
                for (Menu menu : menus) {
                    updateBatch(menu.getMenuId());
                }
            }
        }
    }

    /**
     * @Description: 删除菜单
     * @Param: [fid]
     * @return: com.iking.common.model.Msg
     * @Author: wk
     * @Date: 7/2/2020 上午10:06
     */
    @Override
    public Msg delete(String fid) {
        try {
            Menu model = menuMapper.selectByPrimaryKey(fid);
            if (model == null) {
                return Msg.fail("菜单信息不存在!");
            }
            int count = menuMapper.deleteByPrimaryKey(fid);
            if (count < 1) {
                return Msg.fail("删除菜单失败!");
            }
            return Msg.sucess();
        } catch (Exception e) {
            log.error("删除菜单异常 : " + e);
            return Msg.fail("删除菜单异常!");
        }
    }


    /**
     * @Description: 递归获取子菜单树列表
     * @Param: [tMenu, tMenuList]
     * @return: com.iking.member.system.http.HttpTMenuModel
     * @Author: wk
     * @Date: 12/2/2020 下午6:46
     */
    private HttpMenuModel getMenuToTree(Menu menu, List<Menu> menuList) throws Exception {
        //设置当前菜单响应对象
        HttpMenuModel tMenuRes = new HttpMenuModel();
        tMenuRes.setMenuId(menu.getMenuId());
        tMenuRes.setName(menu.getName());
        tMenuRes.setSort(menu.getSort());
        tMenuRes.setIcon(menu.getIcon());
        tMenuRes.setIsEnable(menu.getIsEnable());
        tMenuRes.setParentId(menu.getParentId());
        tMenuRes.setUrl(menu.getUrl());
        tMenuRes.setIsBtn(menu.getIsBtn());
        tMenuRes.setRemark(menu.getRemark());
        tMenuRes.setLevel(menu.getLevel());
        if (menuList == null || menuList.size() < 1) {
            return tMenuRes;
        }
        //遍历菜单列表寻找子菜单
        List<HttpMenuModel> children = new ArrayList<HttpMenuModel>();        //创建子菜单列表
        for (Menu _Menu : menuList) {                                        //遍历菜单列表
            if (_Menu.getParentId().equals(menu.getMenuId())) {
                children.add(getMenuToTree(_Menu, menuList));
            }
        }
        tMenuRes.setChildren(children);                                            //将子菜单列表设置进响应对象
        return tMenuRes;
    }

    /**
     * @Description: 查询所有
     * @Param: []
     * @return: com.iking.common.model.Msg
     * @Author: wk
     * @Date: 7/2/2020 上午10:09
     */
    @Override
    public Msg selectAll() {
        try {
            List<Menu> resList = menuMapper.selectAll();
            return Msg.sucess(resList);
        } catch (Exception e) {
            log.error("查询所有菜单列表异常 : " + e);
            return Msg.fail("查询所有菜单列表异常!");
        }
    }

    /**
     * @Description: 修改菜单顺序
     * @Param: [req]
     * @return: com.iking.common.model.Msg
     * @Author: wk
     * @Date: 7/2/2020 上午10:09
     */
    @Transactional
    @Override
    public Msg changeSort(HttpMenuChangeSortReq req) {
        try {
            //菜单存在校验
            Menu before = menuMapper.selectByPrimaryKey(req.getBeforeId());
            if (before == null) {
                return Msg.fail("菜单信息不存在!");
            }
            Menu after = menuMapper.selectByPrimaryKey(req.getAfterId());
            if (after == null) {
                return Msg.fail("菜单信息不存在!");
            }
            //设置序号
            after.setSort(req.getBeforeSort());
            before.setSort(req.getAfterSort());
            //修改数据
            menuMapper.updateByPrimaryKey(before);
            menuMapper.updateByPrimaryKey(after);
            return Msg.sucess();
        } catch (Exception e) {
            log.error("修改菜单顺序异常 : " + e);
            return Msg.fail("修改菜单顺序异常!");
        }
    }
}
